﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
using System.Net;
using System.Text;
using System.IO;
using System.Xml;

namespace Hermes.Service
{
    /// <summary>
    /// SalesOrder 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]

    public class SalesOrder : System.Web.Services.WebService
    {

        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }

        [WebMethod]
        public void InsertOrders(Hermes.Model.Orders[] orders)
        {
            Hermes.BLL.Orders ordersBLL = new BLL.Orders();
            foreach (Hermes.Model.Orders order in orders)
            {
                order.Status = (int)Hermes.Model.OrderStatus.BO;
                ordersBLL.Add(order);
            }
            return;
        }


        [WebMethod]
        public string InsertOrder(Hermes.Model.Orders order)
        {
            Hermes.BLL.Orders ordersBLL = new BLL.Orders();
            Hermes.BLL.OrderLines orderLinesBLL = new BLL.OrderLines();
            //foreach (Hermes.Model.Orders order in orders)
            string message = "";

            order.Status = (int)Hermes.Model.OrderStatus.BO;
            try
            {
                Hermes.Model.Orders o = ordersBLL.GetModel(order.OrderNumber, order.SiteID);

                if (o != null)
                {
                    List<Hermes.Model.OrderLines> lines = orderLinesBLL.GetModelList(" OrderNUmber = '" + order.OrderNumber + "'");
                    o.OrderLines = lines;

                    if (o.Status == (int)Hermes.Model.OrderStatus.Shipped)
                    {
                        message = "the order has Shipped";
                    }
                    else if (o.Status == (int)Hermes.Model.OrderStatus.Shipping)
                    {
                        message = "the order is Shipping";
                    }
                    else if (ordersBLL.SameOrder(o, order))
                    {
                        //当订单没有发生改变时，导入成功或失败，操作人员不需要关心
                        message = "0";
                    }
                    else
                    {
                        //TODO：更新订单信息
                        message = "the order has Changed,please contact administator";
                    }
                }
                else
                {
                    ordersBLL.Add(order);
                    message = "0";
                }
            }
            catch (Exception ex)
            {
                message = ex.Message;
            }

            return message;
        }

        [WebMethod]
        public Hermes.Model.WebService.UnCarrierOrdersInfo[] GetUnCarrierOrders(int siteID)
        {
            Hermes.BLL.Orders ordersBLL = new BLL.Orders();
            List<Hermes.Model.WebService.UnCarrierOrdersInfo> result = new List<Model.WebService.UnCarrierOrdersInfo>();
            return ordersBLL.GetUnCarrierOrders(siteID);
        }

        [WebMethod]
        public int AssignCarrier(int carrierID, int siteID, string countries)
        {
            Hermes.BLL.Orders ordersBLL = new BLL.Orders();
            return ordersBLL.AssignCarrier(carrierID, siteID, countries.Split(';'));
        }


        [WebMethod]
        public Hermes.Model.WebService.UnSyncOrderInfo[] GetUnSyncOrders(int carrierID)
        {
            Hermes.BLL.Orders ordersBLL = new BLL.Orders();
            return ordersBLL.UnSyncOrders(carrierID);
        }

        [WebMethod]
        public string SyncEUBOrder(Hermes.Model.WebService.UnSyncOrderInfo order)
        {
            Hermes.BLL.Orders ordersBLL = new BLL.Orders();
            Hermes.BLL.OrderLines orderLinesBLL = new BLL.OrderLines();
            //foreach (Hermes.Model.Orders order in orders)
            string message = "";

            //order.Status = (int)Hermes.Model.OrderStatus.BO;
            Hermes.Model.Orders o = ordersBLL.GetModel(order.Ordernumber, order.SiteID);
            if (o != null)
            {
                List<Hermes.Model.OrderLines> lines = orderLinesBLL.GetModelList(" OrderNUmber = '" + order.Ordernumber + "'");
                o.OrderLines = lines;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.ems.com.cn/partner/api/public/p/order/"); ;
                request.Headers.Add("version", "international_eub_us_1.1");
                request.Headers.Add("authenticate", "lightcastle_826f9e168c3235418332e9e3bd881e5c");
                request.Method = "POST";

                string value = Common.EUBHelper.ToEUBOrdersMessage(o);

                byte[] bytes = Encoding.UTF8.GetBytes(value);
                Stream writer = request.GetRequestStream();
                writer.Write(bytes, 0, bytes.Length);
                writer.Flush();
                writer.Close();

                System.Net.ServicePointManager.Expect100Continue = false;
                WebResponse response = request.GetResponse();
                string str = (new StreamReader(response.GetResponseStream())).ReadToEnd();

                XmlDocument xmldoc = new XmlDocument();


                try
                {
                    xmldoc.Load(new System.IO.MemoryStream(System.Text.Encoding.GetEncoding("GB2312").GetBytes(str)));
                    if (xmldoc.ChildNodes[1].ChildNodes[0].Name == "mailnum")
                    {

                        o.TrackCode = xmldoc.ChildNodes[1].ChildNodes[0].InnerText;


                        if (o.TrackCode != "")
                        {
                            int affectRows = ordersBLL.UpdateTrackingNo(o.OrderNumber, o.SiteID, o.ID, o.TrackCode);
                            if (affectRows != 1)
                            {
                                message = "Something is wrong when update tracking no ";
                            }
                            else
                            {
                                message = "0";
                            }
                        }
                        else
                        {
                            message = "the order info is wrong";
                        }

                    }
                    else
                    {
                        message = "the order info is wrong";
                    }
                }
                catch (Exception ex)
                {
                    message = ex.Message;
                }

            }
            else
            {
                message = "the order dose not Exist";
            }

            return message;
        }

        [WebMethod]
        public Hermes.Model.WebService.UnLabelOrderInfo[] GetUnLabelOrder(int carrierID)
        {
            Hermes.BLL.Orders ordersBLL = new BLL.Orders();
            return ordersBLL.UnLabelOrders(carrierID);
        }

        [WebMethod]
        public Hermes.Model.WebService.LabelResult GetEUBLabel(Hermes.Model.WebService.UnLabelOrderInfo[] orders)
        {
            Hermes.BLL.Orders ordersBLL = new BLL.Orders();
            Hermes.BLL.OrderLines orderLinesBLL = new BLL.OrderLines();

            Hermes.Model.WebService.LabelResult result = new Model.WebService.LabelResult();

            //TODO:订单状态检测
            //foreach (Hermes.Model.Orders order in orders)

            List<int> ids = new List<int>();

            foreach (Hermes.Model.WebService.UnLabelOrderInfo o in orders)
            {
                ids.Add(o.OrderID);
            }


            string message = "";


            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.ems.com.cn/partner/api/public/p/print/batch"); ;
            request.Headers.Add("version", "international_eub_us_1.1");
            request.Headers.Add("authenticate", "lightcastle_826f9e168c3235418332e9e3bd881e5c");
            request.Method = "POST";

            string value = Common.EUBHelper.ToEUBGetLabelMessage(orders);

            byte[] bytes = Encoding.UTF8.GetBytes(value);
            Stream writer = request.GetRequestStream();
            writer.Write(bytes, 0, bytes.Length);
            writer.Flush();
            writer.Close();

            System.Net.ServicePointManager.Expect100Continue = false;
            WebResponse response = request.GetResponse();
            string str = (new StreamReader(response.GetResponseStream())).ReadToEnd();

            XmlDocument xmldoc = new XmlDocument();


            try
            {
                xmldoc.Load(new System.IO.MemoryStream(System.Text.Encoding.GetEncoding("GB2312").GetBytes(str)));
                if (xmldoc.ChildNodes[1].ChildNodes[3].Name == "description")
                {
                    result.URL = xmldoc.ChildNodes[1].ChildNodes[3].InnerText;
                    message = "0";
                    ordersBLL.GetOrdersLabel(ids.ToArray());
                }
                else
                {
                    message = "the order info is wrong";
                }
            }
            catch (Exception ex)
            {
                message = ex.Message;
            }
            result.Message = message;
            return result;
        }

        [WebMethod]
        public string FulfilmentScan(string trackingNo, string shippingUser)
        {
            Hermes.BLL.Orders ordersBLL = new BLL.Orders();
            Hermes.Model.Orders o = ordersBLL.GetModel(trackingNo);
            string message = "";
            if (o == null)
            {
                message = "The trackingno dose not Exist";
            }
            else if (o.Status == (int)Hermes.Model.OrderStatus.GetLabel || o.Status == (int)Hermes.Model.OrderStatus.Picking)
            {
                try
                {
                    int affectRows = ordersBLL.ShipOrder(o.ID, shippingUser);
                    if (affectRows != 1)
                    {
                        message = "Some Wrong";
                    }
                    else message = "0";
                }
                catch (Exception ex)
                {
                    message = ex.Message;
                }
            }
            else if (o.Status == (int)Hermes.Model.OrderStatus.Shipped) message = "order has shipped";
            else message = "order's status is wrong";
            return message;
        }

        [WebMethod]
        public Hermes.Model.WebService.FulfillmentInfo[] GetFulfilInfos(int siteID, int storeID, int carrierID, DateTime startDate, DateTime endDate)
        {
            Hermes.BLL.Orders ordersBLL = new BLL.Orders();
            return ordersBLL.GetFulfilInfos(siteID,storeID,carrierID,startDate,endDate);
        }

    }
}
